package com.yiduo.outpost.core.model.typehandlers;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author xieShangLin
 * @date 2021/12/17 12:38
 */

@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class  ListTypeHandler  extends BaseTypeHandler<List<String>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        String join = String.join(",",parameter);
        ps.setString(i,join);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        if (StringUtils.isBlank(rs.getString(columnName))) {
            return new ArrayList<>();
        }
        return Arrays.asList(rs.getString(columnName).split(","));

    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        if (StringUtils.isBlank(rs.getString(columnIndex))) {
            return new ArrayList<>();
        }
        return Arrays.asList(rs.getString(columnIndex).split(","));
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        if (StringUtils.isBlank(cs.getString(columnIndex))) {
            return new ArrayList<>();
        }
        return Arrays.asList(cs.getString(columnIndex).split(","));
    }
}
